//
//  RZEmojiBoardView.m
//  RZIM
//
//  Created by reyzhang on 2021/8/18.
//

#import "RZEmojiBoardView.h"
#import "RZEmojiTabView.h"
#import "RZIMDefine.h"
#import "RZKitCommonDefine.h"
#import "RZIMConfig.h"



#define RZ_EMOJI_WIDTH 30
#define RZ_EMOTIONTAB_SIZE_HEIGHT 42
#define RZ_EMOTIONTAB_SIZE_WIDTH 42
#define RZ_EMOTIONTAB_ICON_SIZE 25
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

@interface RZEmojiBoardView () <RZEmojiTabViewDelegate>

@property (nonatomic, assign) int emojiTotal;
@property (nonatomic, assign) int emojiTotalPage;
@property (nonatomic, assign) int emojiColumn;
@property (nonatomic, assign) int emojiMaxCountPerPage;
@property (nonatomic, assign) CGFloat emojiMariginHorizontalMin;

@property (nonatomic, strong) NSArray *faceEmojiArray; //表情数据源数组
@property (nonatomic, assign) int emojiLoadedPage;

@property (nonatomic, strong) UIPageControl *pageCtrl;
@property (nonatomic, strong) RZEmojiTabView *tabbarView; //表情组管理工具条view
@property (nonatomic, assign) CGSize emojiContentSize; //默认的emoji 的contentSize
@property (nonatomic, assign) int preSelectEmoticonPackageIndex;

@end



static int currentSelectIndexPage; //当前选中的索引页
@implementation RZEmojiBoardView {
    /*!
     当前所在页的索引值
     */
    //  NSInteger currentIndex;

    CGFloat lastFrameWith;
}


#pragma mark - Life Cycle
- (instancetype)initWithFrame:(CGRect)frame delegate:(id<RZEmojiViewDelegate>)delegate {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        currentSelectIndexPage = 0;
        
        //读取资源
        NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
        NSString *bundlePath = [resourcePath stringByAppendingPathComponent:@"Emoji.plist"];
        
        self.faceEmojiArray = [[NSArray alloc] initWithContentsOfFile:bundlePath];
        self.emojiLoadedPage = 0;

        //生成默认的布局参数
        [self generateDefaultLayoutParameters];
        
        //表情容器
        lastFrameWith = self.frame.size.width;
        self.emojiBackgroundView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 186)];
        self.emojiBackgroundView.backgroundColor = [UIColor colorWithRed:242/255.0 green:244/255.0 blue:248/255.0 alpha:1];
        self.emojiBackgroundView.pagingEnabled = YES;
        self.emojiBackgroundView.contentSize = CGSizeMake(self.emojiTotalPage * self.frame.size.width, 186);
        self.emojiBackgroundView.showsHorizontalScrollIndicator = NO;
        self.emojiBackgroundView.showsVerticalScrollIndicator = NO;
        self.emojiBackgroundView.delegate = self;
       
        self.delegate = delegate;
        [self addSubview:self.emojiBackgroundView];
        [self loadLabelView];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Super Methods

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    if (fabs(frame.size.width - lastFrameWith) >= 4) {
        lastFrameWith = frame.size.width;
    } else {
        return; //防止页面过度刷新
    }
    // 配置本页视图动态变化 ========================= 开始//
    if (_tabbarView) {
        CGRect tabbarViewFrame = _tabbarView.frame;
        tabbarViewFrame.size.width = frame.size.width;
        self.tabbarView.frame = tabbarViewFrame;
    }
    
    // 配置本页视图动态变化 ========================= 结束//

    [self generateDefaultLayoutParameters];
    // 调整现实布局
    for (UIView *subView in self.emojiBackgroundView.subviews) {
        // 先把表情类视图移除
        if (![subView isKindOfClass:[UIScrollView class]]) {
            [subView removeFromSuperview];
        }
    }

    self.emojiLoadedPage = 0;
    [self.emojiBackgroundView setContentOffset:CGPointMake(0, 0) animated:YES];
    // 能不能不重新初始化视图
    //[self loadEmojiViewPartly];
    self.emojiContentSize = CGSizeMake(self.emojiTotalPage * self.frame.size.width, 186);

    CGSize size = self.emojiContentSize;
    size.width = self.emojiContentSize.width + self.frame.size.width * 0;
    self.emojiBackgroundView.contentSize = size;
}

//用于动画效果
- (void)setHidden:(BOOL)hidden {
    CGRect viewRect = self.frame;
    if (hidden) {
        viewRect.origin.y = [self getBoardViewBottonOriginY];
    } else {
        viewRect.origin.y = [self getBoardViewBottonOriginY] - self.frame.size.height;
    }
    [self setFrame:viewRect];
    [super setHidden:hidden];
}

#pragma mark - Public Methods
- (void)loadLabelView {
    [self loadEmojiViewPartly];
    
    [self addSubview:self.pageCtrl];
    [self addSubview:self.tabbarView];
    
    [self.tabbarView showAddButton:NO showSettingButton:NO];
    [self loadCustomerEmoticonPackage]; //加载默认表情
}

- (void)enableSendButton:(BOOL)enableSend {
    UIButton *sendButton = (UIButton *)[self.tabbarView viewWithTag:333];
    if (enableSend) {
        sendButton.userInteractionEnabled = YES;
        sendButton.backgroundColor = [UIColor colorWithRed:17/255.0 green:131/255.0 blue:254/255.0 alpha:1];
        [sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    } else {
        sendButton.userInteractionEnabled = NO;
        sendButton.backgroundColor = [UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1];
        [sendButton setTitleColor:[UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1] forState:UIControlStateNormal];
    }
}

#pragma mark Private Method

//延迟加载emoji表情
- (void)loadEmojiViewPartly {
    //每次加载两页，防止快速移动
    int beginEmojiBtn = self.emojiLoadedPage * self.emojiMaxCountPerPage;
    int endEmojiBtn = MIN(self.emojiTotal, (self.emojiLoadedPage + 2) * self.emojiMaxCountPerPage);
    
    float startPos_X = 0, startPos_Y = 26.5;
    startPos_X = self.emojiMariginHorizontalMin + 6;
    
    
    for (int i = beginEmojiBtn; i < endEmojiBtn; i++) {
        int pageIndex = i / self.emojiMaxCountPerPage;
        float emojiPosX =
            startPos_X + 42 * (i % self.emojiMaxCountPerPage % self.emojiColumn) + pageIndex * self.frame.size.width;
        float emojiPosY = startPos_Y + 47 * (i % self.emojiMaxCountPerPage / self.emojiColumn);
        UIButton *emojiBtn =
            [[UIButton alloc] initWithFrame:CGRectMake(emojiPosX, emojiPosY, RZ_EMOJI_WIDTH, RZ_EMOJI_WIDTH)];
        emojiBtn.titleLabel.font = [RZIMConfigCenter.font fontOfSize:26];
        [emojiBtn setTitle:self.faceEmojiArray[i] forState:UIControlStateNormal];
        [emojiBtn addTarget:self action:@selector(emojiBtnHandle:) forControlEvents:UIControlEventTouchUpInside];
        [self.emojiBackgroundView addSubview:emojiBtn];
        if (((i + 1) >= self.emojiMaxCountPerPage && (i + 1) % self.emojiMaxCountPerPage == 0) ||
            i == self.emojiTotal - 1) {
            CGRect frame = emojiBtn.frame;
            UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [deleteButton addTarget:self
                             action:@selector(emojiBtnHandle:)
                   forControlEvents:UIControlEventTouchUpInside];
            int offset = 30;
            frame.origin.x = self.frame.size.width - startPos_X - offset + pageIndex * self.frame.size.width;
            frame.size = CGSizeMake(RZ_EMOJI_WIDTH, RZ_EMOJI_WIDTH);
            deleteButton.frame = frame;
            [deleteButton setImage:RZResourceImage(@"emoji_btn_delete") forState:UIControlStateNormal];
            deleteButton.contentEdgeInsets = UIEdgeInsetsMake(3, 0, 0, 0);
            [self.emojiBackgroundView addSubview:deleteButton];
        }
        if (self.emojiLoadedPage < pageIndex + 1) {
            self.emojiLoadedPage = pageIndex + 1;
        }
    }
    self.emojiContentSize = self.emojiBackgroundView.contentSize;
}

/**
 初始化默认的布局参数
 */
- (void)generateDefaultLayoutParameters {
    CGFloat emojiSpanHorizontal = 42; //一个emoji表情占的宽度
    
    int emojiRow = 3; //显示3行
    self.emojiMariginHorizontalMin = 6;
    if (nil == self.faceEmojiArray || [self.faceEmojiArray count] == 0) {
        self.emojiTotal = 0;
    } else {
        self.emojiTotal = (int)[self.faceEmojiArray count]; //emoji表情总数
    }
    
    //计算能容纳多少列
    self.emojiColumn = (int)(self.frame.size.width / emojiSpanHorizontal); // 能够容纳多少列
    int left = ((int)self.frame.size.width) % 42; //计算剩余的左边距，用来做适配，当前屏幕可允许最大显示的列数
    if (left < 12) { //如果小于指定的12，则减1列
        self.emojiColumn--;
        left = left + emojiSpanHorizontal;
    }
    
    //每页所允许显示的emoji的数量  列*行 - 删除按钮占的位置
    self.emojiMaxCountPerPage = self.emojiColumn * emojiRow - 1;
    
    self.emojiMariginHorizontalMin = left / 2;
    
    //计算emoji显示的总页数
    self.emojiTotalPage =
        self.emojiTotal / self.emojiMaxCountPerPage + (self.emojiTotal % self.emojiMaxCountPerPage ? 1 : 0);
}


//然后是点击UIPageControl时的响应函数pageTurn
- (void)pageTurn:(UIPageControl *)sender {
    int index = (int)sender.currentPage;
    currentSelectIndexPage = 0;
    [self showEmoticonPackage:index];
}

- (float)getBoardViewBottonOriginY {
    float gap = (RZ_IOS_SYSTEM_VERSION_LESS_THAN(@"7.0")) ? 64 : 0;
    return [UIScreen mainScreen].bounds.size.height - gap;
}


- (void)showEmoticonPackage:(int)index {
    int selectIndex = index;
    if (selectIndex <= 0) {
        self.pageCtrl.numberOfPages = self.emojiTotalPage;
    }
    CGSize viewSize = self.emojiBackgroundView.frame.size;
    CGRect rect = CGRectMake(selectIndex * viewSize.width, 0, viewSize.width, viewSize.height);
    [self.emojiBackgroundView scrollRectToVisible:rect animated:NO];
    [self.pageCtrl setCurrentPage:index];
    
    _preSelectEmoticonPackageIndex = index;
    [self showEmoticonView:index];
    [self.tabbarView showEmotion:index];
}


- (void)showEmoticonView:(int)index {
    //    //令UIScrollView做出相应的滑动显示
    while (self.emojiLoadedPage <= index && (self.faceEmojiArray && self.faceEmojiArray.count > 0)) {
        [self loadEmojiViewPartly];
    }
    CGSize viewSize = self.emojiBackgroundView.frame.size;
    CGRect rect = CGRectMake(index * viewSize.width, 0, viewSize.width, viewSize.height);
    [self.emojiBackgroundView scrollRectToVisible:rect animated:YES];
    [self.pageCtrl setCurrentPage:index];
}


/**
 加载表情包
 */
- (void)loadCustomerEmoticonPackage {
    UIImage *image = RZResourceImage(@"emoji_btn_normal");
    NSMutableArray *emojiList = @[].mutableCopy;
    if (image) {
        [emojiList addObject:image];
    }
    
    [self.tabbarView reloadTabView:emojiList];
    [self showEmoticonPackage:0];
        
}


- (void)emojiBtnHandle:(UIButton *)sender {
    if ([self.delegate respondsToSelector:@selector(didTouchEmojiView:touchedEmoji:)]) {
        [self.delegate didTouchEmojiView:self touchedEmoji:sender.titleLabel.text];
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self loadEmojiViewPartly];
}

//停止滚动的时候
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //更新UIPageControl的当前页
    CGPoint offset = scrollView.contentOffset;
    CGRect bounds = scrollView.frame;
    int currentIndex = offset.x / bounds.size.width;
    int selectIndex = currentIndex;
    
    if (currentIndex < self.emojiTotalPage) {
        self.pageCtrl.numberOfPages = self.emojiTotalPage;
        currentSelectIndexPage = currentIndex;
        if (self.emojiLoadedPage <= currentIndex) {
            [self showEmoticonView:currentIndex];
        }
    }
    
    [self.tabbarView showEmotion:0];
    [self.pageCtrl setCurrentPage:selectIndex];
}

#pragma mark - RCEmojiTabViewDelegate

- (void)emojiTabView:(RZEmojiTabView *)emojiTabView didClickSendButton:(UIButton *)button{
    if ([self.delegate respondsToSelector:@selector(didSendButtonEvent:sendButton:)]) {
        [self.delegate didSendButtonEvent:self sendButton:button];
    }
}

- (void)emojiTabView:(RZEmojiTabView *)emojiTabView didSelectEmotion:(int)index {
    
}

#pragma mark - Getters and Setters
- (CGSize)contentViewSize {
    return CGSizeMake(self.frame.size.width, 186);
}

- (RZEmojiTabView *)tabbarView{
    if (!_tabbarView) {
        _tabbarView = [[RZEmojiTabView alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 38, self.frame.size.width, 38)];
        _tabbarView.backgroundColor = [UIColor whiteColor];
        _tabbarView.delegate = self;
    }
    return _tabbarView;
}

- (UIPageControl *)pageCtrl {
    if (!_pageCtrl) {
        _pageCtrl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 175, self.frame.size.width, 5)];
        _pageCtrl.numberOfPages = self.emojiTotalPage; //总的图片页数
        _pageCtrl.currentPage = 0;                     //当前页
        
        _pageCtrl.currentPageIndicatorTintColor = [UIColor colorWithRed:115/255.0 green:115/255.0 blue:115/255.0 alpha:1];
        _pageCtrl.pageIndicatorTintColor = [UIColor colorWithRed:177/255.0 green:177/255.0 blue:177/255.0 alpha:1];
        _pageCtrl.hidesForSinglePage = YES; //只一页时隐藏

        [_pageCtrl addTarget:self action:@selector(pageTurn:) forControlEvents:UIControlEventValueChanged];
    }
    return _pageCtrl;
}


@end
